package com.leen.admin.service.impl;

import com.leen.admin.dto.DictDTO;
import com.leen.admin.entity.Dict;
import com.leen.admin.repository.AdminRepository;
import com.leen.admin.repository.DictRepository;
import com.leen.admin.service.DictService;
import com.leen.common.vo.ResponseVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yy
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class DictServiceImpl extends CurdServiceImpl<Dict,Long> implements DictService {


    private DictRepository dictRepository;

    @Autowired
    public void setDictRepository(DictRepository dictRepository){
        this.dictRepository=dictRepository;
        super.setCrudRepository(dictRepository);
    }

    @Override
    public ResponseVO serach(DictDTO dictDTO) {
        //分页页码
        Pageable pageable = PageRequest.of(dictDTO.getPageNumber()-1,dictDTO.getPageSize());
        //构建查询对象
        Specification<Dict> specification = new Specification<Dict>() {
            @Override
            public Predicate toPredicate(Root<Dict> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> arr = new ArrayList<>();
                if(StringUtils.isNotBlank(dictDTO.getName())){
                    arr.add(criteriaBuilder.like(root.get("name"),"%"+dictDTO.getName()+"%"));
                }
                return criteriaBuilder.and(arr.toArray(new Predicate[arr.size()]));
            }
        };
        Page<Dict> page = this.dictRepository.findAll(specification,pageable);
        return new ResponseVO(page.getTotalElements(),page.getContent());
    }
}
